package com.shopping.shoppingdemo.service;

import com.shopping.shoppingdemo.domain.vo.AfterSaleSummary;
import com.shopping.shoppingdemo.domain.dto.AuditResult;
import com.shopping.shoppingdemo.domain.dto.CreateAfterSaleRequest;
import com.shopping.shoppingdemo.domain.po.AfterSaleOrder;
import com.shopping.shoppingdemo.enums.AuditAction;
import com.shopping.shoppingdemo.utils.TimeUtils;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Service
public class AfterSaleService {
    private final ConcurrentHashMap<String, AfterSaleOrder> storage = new ConcurrentHashMap<>();
    private final List<String> orderList = new CopyOnWriteArrayList<>();


    public AfterSaleOrder create(CreateAfterSaleRequest req) {
        String id = UUID.randomUUID().toString();
        AfterSaleOrder o = new AfterSaleOrder(id);
        o.setProductName(req.productName.trim());
        o.setPurchaseStore(req.purchaseStore.trim());
        o.setPurchaseAmountCents(req.purchaseAmountCents);
        o.setProblemDescription(req.problemDescription.trim());
        o.setContactPhone(req.contactPhone.trim());
        o.setPurchaseTime(TimeUtils.parseToInstant(req.purchaseTime));
        storage.put(id, o);
        orderList.add(id);
        return o;
    }


    public List<AfterSaleSummary> query(Optional<String> productNameOpt, Optional<Instant> startOpt, Optional<Instant> endOpt) {
        return orderList.stream()
                .map(storage::get)
                .filter(Objects::nonNull)
                .filter(o -> {
                    boolean ok = true;
                    if (productNameOpt.isPresent()) {
                        ok = o.getProductName().toLowerCase().contains(productNameOpt.get().toLowerCase());
                    }
                    if (ok && startOpt.isPresent()) ok = !o.getPurchaseTime().isBefore(startOpt.get());
                    if (ok && endOpt.isPresent()) ok = !o.getPurchaseTime().isAfter(endOpt.get());
                    return ok;
                })
                .map(o -> new AfterSaleSummary(o.getId(), o.getProductName(), o.getPurchaseTime(), o.getProblemDescription()))
                .collect(Collectors.toList());
    }


    public AfterSaleOrder getById(String id) {
        return storage.get(id);
    }


    public AuditResult audit(String id, String operator, AuditAction action, String comment) {
        AfterSaleOrder o = storage.get(id);
        if (o == null) return new AuditResult(false, "售后单不存在");
        try {
            return o.audit(operator, action, comment);
        } catch (Exception e) {
            return new AuditResult(false, "操作异常: " + e.getMessage());
        }
    }
}